package api;

import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-11-08
 * Time: 20:06
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || password == null || "".equals(password) || "".equals(username)){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前传回来的参数为空");
            return;
        }
        UserDao userDao = new UserDao();
        try {
            User user = userDao.serachByusername(username);
            if(user == null){
                resp.setContentType("text/html; charset=utf8");
                resp.getWriter().write("用户名或者密码错误");
                return;
            }
            if(!user.getPassword().equals(password)){
                resp.setContentType("text/html; charset=utf8");
                resp.getWriter().write("用户名或者密码错误");
                return;
            }
            System.out.println(user.getUserId());
            HttpSession session = req.getSession(true);
            session.setAttribute("user", user);
            User user1 = (User) session.getAttribute("user");
            System.out.println(user1.getUserId());
            resp.sendRedirect("blog_list.html");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if(session == null){
            resp.setStatus(403);
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            resp.setStatus(403);
            return;
        }
        resp.setStatus(200);
    }
}
